package com.cloudeasy.post.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloudeasy.api.vo.PageResult;
import com.cloudeasy.api.vo.post.SimpleUserInfoVO;
import com.cloudeasy.api.vo.post.StoreyVO;
import com.cloudeasy.post.po.Storey;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 回复工具类
 */
public class StoreyUtil {
    /**
     * 转换VO对象
     *
     * @param storey              {@link Storey}
     * @param simpleUserInfoVOMap {@link Map<String, SimpleUserInfoVO>}
     * @return {@link StoreyVO}
     */
    public static StoreyVO convert(Storey storey, Map<String, SimpleUserInfoVO> simpleUserInfoVOMap) {
        StoreyVO storeyVO = new StoreyVO();
        BeanUtils.copyProperties(storey, storeyVO);
        storeyVO.setAnswerer(simpleUserInfoVOMap.get(storey.getAnswererId()));
        return storeyVO;
    }

    /**
     * 转换VO对象
     *
     * @param storeys           {@link List<Storey>}
     * @param simpleUserInfoVOS {@link List<SimpleUserInfoVO>}
     * @return {@link List<StoreyVO>}
     */
    public static List<StoreyVO> convert(List<Storey> storeys, List<SimpleUserInfoVO> simpleUserInfoVOS) {
        Map<String, SimpleUserInfoVO> simpleUserInfoVOMap = toMap(simpleUserInfoVOS);
        if (storeys != null && storeys.size() > 0) {
            return storeys.stream().map(storey -> convert(storey, simpleUserInfoVOMap)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 转换VO对象
     *
     * @param storeyIPage       {@link IPage<Storey>}
     * @param simpleUserInfoVOS {@link List<SimpleUserInfoVO>}
     * @return {@link PageResult<StoreyVO>}
     */
    public static PageResult<StoreyVO> convert(IPage<Storey> storeyIPage, List<SimpleUserInfoVO> simpleUserInfoVOS) {
        Map<String, SimpleUserInfoVO> simpleUserInfoVOMap = toMap(simpleUserInfoVOS);
        PageResult<StoreyVO> storeyVOPageResult = new PageResult<>();
        storeyVOPageResult.setTotal(storeyIPage.getTotal())
                .setPages(storeyIPage.getPages())
                .setRecords(storeyIPage.getRecords().stream().map(storey -> convert(storey, simpleUserInfoVOMap)).collect(Collectors.toList()));
        return storeyVOPageResult;
    }

    /**
     * 将简单用户信息列表转化为Id为key的Map
     *
     * @param simpleUserInfoVOS {@link List<SimpleUserInfoVO>}
     * @return {@link Map<String, SimpleUserInfoVO>}
     */
    private static Map<String, SimpleUserInfoVO> toMap(List<SimpleUserInfoVO> simpleUserInfoVOS) {
        return simpleUserInfoVOS.stream().collect(Collectors.toMap(SimpleUserInfoVO::getId, simpleUserInfoVO -> simpleUserInfoVO, (o, o2) -> o));
    }
}
